package com.gs.m_home.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.gs.m_home.R
import com.gs.common.data.Good

class GoodsListAdapter(context: Context, data: ArrayList<Good>): RecyclerView.Adapter<GoodsListAdapter.GoodsListViewHolder>() {

    private val data: ArrayList<Good>
    private val context: Context

    private var mOnItemClickListener: OnGoodsListItemClickListener? = null

    inner class GoodsListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val picture: ImageView
        val title: TextView
        val price: TextView

        init {
            picture = itemView.findViewById(R.id.goos_picture)
            title = itemView.findViewById(R.id.goods_title)
            price = itemView.findViewById(R.id.goods_price)

            itemView.setOnClickListener {
                if (mOnItemClickListener != null) {
                    mOnItemClickListener?.onItemClick(adapterPosition)
                }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GoodsListViewHolder {
        val view = View.inflate(context, R.layout.goods_list_item, null)
        return GoodsListViewHolder(view)
    }

    override fun getItemCount(): Int {
        return data.size
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: GoodsListViewHolder, position: Int) {
        Glide.with(context).load(data[position].picture_path).into(holder.picture)
        holder.title.text = data[position].title
        holder.price.text = "￥" + data[position].price.toString()
    }

    interface OnGoodsListItemClickListener {
        fun onItemClick(position: Int)
    }

    fun setGoodsListItemClickListener(listener: OnGoodsListItemClickListener) {
        mOnItemClickListener = listener
    }

    fun removeGoodsListItemClickListener() {
        if (mOnItemClickListener != null) {
            mOnItemClickListener = null
        }
    }


    init {
        this.data = data
        this.context = context
    }

}